package com.zxtc.wh.service.appVersion;

import com.zxtc.wh.servlet.appVersion.AppUploadVersionBean;
import com.zxtc.wh.pojo.appVersion.AppVersionBean;
import com.zxtc.wh.pojo.resource.Resource;
import com.zxtc.wh.pojo.resource.SimpleResourceInfoBean;
import com.zxtc.wh.service.IResourceService;
import com.zxtc.wh.service.ResourceServiceImpl;

import java.io.*;
import java.util.Objects;
import java.util.function.Function;

/**
 * app应用更新的
 */
public class AppUpdateVersionServiceImpl implements IAppUpdateVersionService {
    Mapper mapper;
    IResourceService resourceService;


    public AppUpdateVersionServiceImpl(Mapper mapper, IResourceService resourceService) {
        this.mapper = mapper;
        this.resourceService = resourceService;
    }

    public AppUpdateVersionServiceImpl() {
        mapper = new Mapper();
        this.resourceService = new ResourceServiceImpl();
    }

    @Override
    public void insert(AppVersionBean version) {

    }

    public AppVersionBean map(AppUploadVersionBean uploadBean) {
        return mapper.apply(uploadBean);
    }


    /**
     * 将用户的输入解析为需要格式的工具类
     */
    private class Mapper implements Function<AppUploadVersionBean, AppVersionBean> {
        @Override
        public AppVersionBean apply(AppUploadVersionBean uploadBean) {
            Objects.requireNonNull(uploadBean);//校验断言非空
            AppVersionBean appVersionBean = new AppVersionBean();

            //初始化返回值
            try {
                SimpleResourceInfoBean infoBean = resourceService.resourceInfo(uploadBean.getAppFile(), uploadBean.getAppFileFileName());
                InputStream inputStream;
                inputStream = new BufferedInputStream(new FileInputStream(uploadBean.getAppFile()));
                Resource resource = resourceService.upload(inputStream, infoBean);
                appVersionBean.setUpdateResource(resource);


                appVersionBean.setHandler(AppUpdateVersionServiceImpl.this.updateVersionHandle(
                        uploadBean.getResourceType(),
                        uploadBean.getDownloadType(),
                        uploadBean.getRestartType(),
                        uploadBean.getInstallType()
                ));
                appVersionBean.setAppIdentifier(Integer.valueOf(uploadBean.getAppIdentifier()));
            } catch (Exception e) {
                //接力抛出异常
                throw new RuntimeException(e);

//                //抛出异常则返回null
//                return null;
            }

            return appVersionBean;
        }
    }
}

